<?php
/**
 * Created by 13129484282@163.com.
 * User: lwt
 * Date: 2018/4/17
 * Time: 10:28
 */

namespace app\api\controller\books;



use think\Db;

class AuthBase extends Base
{
    public static $rule = [

    ];
    public $user;

    protected function _initialize()
    {
        parent::_initialize();

        $this->params = $this->check_access_token($this->params);
      //检测是否能加积分
      if(isset($this->user['vip']) && $this->user['vip']) {
        $point_rule = db("gzns_point_rule")->find();
        $today_point_count = db("gzns_user_point")
          ->where('user_id', $this->user['id'])
          ->where('type', 1)
          ->where('create_time', '>=', date('Y-m-d 00:00:00'))
          ->count();

        if (!$today_point_count) {
          // 乐观锁
          $res = db("gzns_userInfo")
            ->where("id", $this->user['id'])
            ->where("version", $this->user['version'])
            ->update([
              "point" => $point_rule['vip_login_point'] + $this->user['point'],
              "version" => 1 + $this->user['version'],
            ]);
          if($res) {
            db("gzns_user_point")->insert([
              'user_id' => $this->user['id'],
              'point' => $point_rule['vip_login_point'],
              'type' => 1,
            ]);
          }
        }
      }

    }
    public function setUser(){
        //查询会员信息


    }
    public function check_access_token($arr)
    {
        /************* api传过来的token ***************/
        if (!isset($arr['access_token']) || empty($arr['access_token'])) {
            $this->return_msg(401, 'access_token不能为空!');
        }
        $app_token = $arr['access_token'];//api传过来的token
        /************* 验证access_token ***************/
        $res = db('oauth_users')->where('oauth_user_access_token', $arr['access_token'])->find();
        if ($res) {
            $arr['uid'] = $res['user_id'];
            //TODO 身份放行
            $user=db('gzns_user_info')->where(['id'=>$res['user_id']])->find();
            if (!$user) {
                $this->return_msg(400, '非法访问,用户不存在！');
            }
            if (!$user['status']) {
                $this->return_msg(400, '非法访问,用户已被冻结！');
            }
            $this->user = $user;
          $aptitude = db("gzns_user_vip_apply")
            ->where("user_id",$this->user["id"])
            ->where('status',1)
            ->find();
          $user_vip = db('gzns_user_vip_level uvl')->where('uvl.user_id', $this->user["id"])->find();
          if ($user_vip) {
            $this->user['vip'] = $user_vip;
          } else {
            $this->user['vip'] = null;
          }
          if ($aptitude) {
            $this->user['vip_apply'] = $aptitude;
          }
          //审核版本
          $this->user['check_version'] = 1;
            return $arr;
        } else {
            $this->return_msg(401, '无效的access_token!');
        }
    }

}
